package com.js.auth.server.runner;

import com.alibaba.fastjson.JSON;
import com.js.auth.server.config.KeyConfig;
import com.js.auth.server.module.client.entity.GatewayRoute;
import com.js.auth.server.module.client.service.GatewayRouteService;
import com.js.common.constant.RedisKeyConstants;
import com.js.core.util.RsaKeyHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author： ygl
 * @date： 2018/10/27
 * @Description：
 * 授权服务器启动时执行以下操作：
 * 1。更新网关路由
 * 2。生成用户token加密的公钥/密钥
 *
 */
@Slf4j
@Configuration
public class AuthServerRunner implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private GatewayRouteService gatewayRouteService;

    @Autowired
    private KeyConfig keyConfig;

    @Autowired
    private RsaKeyHelper rsaKeyHelper;

    @Override
    public void run(String... args) throws Exception {
        // 1。更新网关路由
        List<GatewayRoute> gatewayRoutes = gatewayRouteService.selectAll();
        redisTemplate.opsForValue().set(RedisKeyConstants.ZUUL_ROUTE_KEY, JSON.toJSONString(gatewayRoutes));
        log.info("********************完成网关路由的更新***********************");
        //2。初始化公钥/密钥
        boolean flag = false;
        if (redisTemplate.hasKey(RedisKeyConstants.REDIS_USER_PRI_KEY)&&redisTemplate.hasKey(RedisKeyConstants.REDIS_USER_PUB_KEY)){
            try {
                keyConfig.setUserPriKey(rsaKeyHelper.toBytes(redisTemplate.opsForValue().get(RedisKeyConstants.REDIS_USER_PRI_KEY).toString()));
                keyConfig.setUserPubKey(rsaKeyHelper.toBytes(redisTemplate.opsForValue().get(RedisKeyConstants.REDIS_USER_PUB_KEY).toString()));
            }catch (Exception e){
                log.error("********************初始化用户公钥/密钥异常***********************",e);
                flag = true;
            }
        }
        if(flag){
            Map<String, byte[]> keyMap = rsaKeyHelper.generateKey(keyConfig.getUserSecret());
            keyConfig.setUserPriKey(keyMap.get("pri"));
            keyConfig.setUserPubKey(keyMap.get("pub"));
            redisTemplate.opsForValue().set(RedisKeyConstants.REDIS_USER_PRI_KEY, rsaKeyHelper.toHexString(keyMap.get("pri")));
            redisTemplate.opsForValue().set(RedisKeyConstants.REDIS_USER_PUB_KEY, rsaKeyHelper.toHexString(keyMap.get("pub")));
        }
        log.info("********************完成用户公钥/密钥的初始化***********************");
    }
}
